import { Card, Button, Checkbox, Form, Input, message } from "antd";
import logo from "../../assets/logo.png";
import "./index.scss";
import { useDispatch } from "react-redux";
import { loginAction } from "@/store/modules/login";
import { useNavigate } from "react-router-dom";

const Login = () => {
  const dis = useDispatch();
  const nav = useNavigate();
  const onFinish = async (formData) => {
    try {
      await dis(loginAction(formData));
      message.success("登录成功");
      nav("/");
    } catch (error) {
      message.error(error.response.data.message);
    }
  };

  const validCode = (rule, value) => {
    if (!value) {
      return Promise.reject(new Error("请勾选用户协议！"));
    }
    return Promise.resolve();
  };
  return (
    <div className="login">
      {/* <hr />
      <Forms />
      <Forms.Items /> */}
      <Card className="login-container">
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
        <Form
          // 校验触发时机
          validateTrigger={["onBlur", "onChange"]}
          // 表单变量初始化值
          initialValues={{
            // 测试账号
            mobile: "13911111111",
            code: "246810",
            agree: true,
          }}
          onFinish={onFinish}
          autoComplete="off"
        >
          {/* 1. 手机号 */}
          <Form.Item
            // name定义表单变量名叫啥=》后台登录接口参数名
            name="mobile"
            // rules指定校验规则
            rules={[
              {
                pattern:
                  /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
                message: "手机号码格式不对",
                validateTrigger: "onBlur",
              },
              { required: true, message: "请输入手机号" },
            ]}
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>
          {/* 2. 验证码 */}
          <Form.Item
            name="code"
            rules={[
              { len: 6, message: "验证码6个字符", validateTrigger: "onBlur" },
              { required: true, message: "请输入验证码" },
            ]}
          >
            <Input placeholder="请输入验证码" />
          </Form.Item>
          {/* 3. 使用协议 */}
          <Form.Item
            name="agree"
            rules={[
              {
                // 提供校验函数
                validator: validCode,
              },
            ]}
            valuePropName="checked"
          >
            <Checkbox>我已阅读并同意「用户协议」和「隐私条款」</Checkbox>
          </Form.Item>
          {/* 4. 登录按钮 =》 htmlType="submit" 指定作为表单提交的按钮 */}
          <Form.Item>
            <Button size="large" type="primary" htmlType="submit" block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Login;
